import { Share, User } from '../models';
import shortid from 'shortid';
import moment from 'moment';

export default function (router) {
  // 获取用户的分享信息
  router.get('/api/front/share/info', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    // 查询当前用户的邀请信息，如果找不到则创建一个
    let hisShareInfo = await Share.findOne({ userid });
    if (!hisShareInfo) {
      const code = shortid.generate();
      hisShareInfo = await Share.create({
        // @ts-ignore
        userid: ctx.transId(userid),
        code,
        award_records: [],
        accept_records: [],
        create_time: new Date()
      });
    }
    // 统计用户邀请信息，今日邀请人数，以及累计邀请人数，累计获得书书币数
    const nowDateStr = moment().format('YYYY/MM/DD');
    const startTime = new Date(nowDateStr + ' 00:00:00');
    const endTime = new Date(nowDateStr + ' 24:00:00');
    let todayInviteNum = 0;
    let totalInviteNum = 0;
    let todayAwardNum = 0;
    let totalAwardNum = 0;
    let users = [];
    hisShareInfo.accept_records.forEach(item => {
      const time = item.accept_time.getTime();
      if (time >= startTime.getTime() && time <= endTime.getTime()) {
        todayInviteNum++;
      }
      const uid = item.uid.toString();
      if (users.indexOf(uid) < 0) {
        users.push(uid);
        totalInviteNum++;
      }
    });
    hisShareInfo.award_records.forEach(item => {
      const time = item.award_time.getTime();
      if (time >= startTime.getTime() && time <= endTime.getTime()) {
        todayAwardNum += item.amount;
      }
      totalAwardNum += item.amount;
    });
    await ctx.json(true, 'success', {
      shareInfo: {
        todayAwardNum,
        todayInviteNum,
        totalAwardNum,
        totalInviteNum
      },
      awardRecords: hisShareInfo.award_records.map(item => {
        return {
          name: item.user || '--',
          type: item.name.replace('奖励', ''),
          time: moment(item.award_time).format('YYYY/MM/DD')
        };
      })
    });
  });

  // 更新分享记录，在每次被邀请用户登录之后
  router.get('/api/front/share/update', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const shareCode = ctx.request.query.share_code;
    const reg = /^[A-Za-z0-9-_]+(\||@)\d+$/;
    if (!shareCode || !reg.test(shareCode)) {
      await ctx.json(false, '参数错误');
      return;
    }
    const code = shareCode.split(/(\||@)/)[0];
    const time = new Date(parseInt(shareCode.split(/(\||@)/)[1]));
    const thisShareLog = await Share.findOne({ code });
    if (!thisShareLog) {
      await ctx.json(false, '参数错误\r\n找不到分享记录');
      return;
    }
    // 限制自己不能邀请自己
    if (thisShareLog.userid.toString() === userid) {
      await ctx.json(false, '参数错误\r\n自己不能邀请自己', { inviteself: true });
      return;
    }
    const now = new Date();
    if (now.getTime() - time.getTime() >= 24 * 60 * 60 * 1000) {
      await ctx.json(false, '邀请已经过期');
      return;
    }
    // 判断当前用户今天是否已经被别的用户邀请过了
    const nowDateStr = moment().format('YYYY/MM/DD');
    const startTime = new Date(nowDateStr + ' 00:00:00');
    const endTime = new Date(nowDateStr + ' 24:00:00');
    const hasInviteLog = await Share.find({ 'accept_records.uid': userid, 'accept_records.accept_time': { $gte: startTime, $lte: endTime } }, '_id accept_records');
    const hasBeInvited = hasInviteLog.some(item => {
      return item.accept_records.length > 0;
    });
    // 新增接受分享的记录
    await Share.updateOne(
      { code },
      {
        $addToSet: {
          accept_records: {
            uid: ctx.transId(userid),
            accept_time: now
          }
        }
      }
    );
    if (hasBeInvited) {
      await ctx.json(false, '您今天已经接受过邀请了');
    } else {
      // @ts-ignore 分发奖励
      const acceptAward = await User.addAmount(userid, 15, '接收他人邀请奖励');
      // @ts-ignore
      const launchAward = await User.addAmount(thisShareLog.userid.toString(), 15, '邀请他人登录奖励');
      if (acceptAward && launchAward) {
        // 新增奖励记录
        let launchUser = await User.findById(thisShareLog.userid.toString(), 'username');
        await Share.updateOne(
          { userid },
          {
            $addToSet: {
              award_records: {
                name: '接受邀请奖励',
                user: launchUser ? launchUser.username : '',
                amount: 15,
                award_time: new Date()
              }
            }
          }
        );
        const currentUser = await User.findById(userid, 'username');
        await Share.updateOne(
          { code },
          {
            $addToSet: {
              award_records: {
                name: '邀请别人奖励',
                amount: 15,
                user: currentUser ? currentUser.username : '',
                award_time: new Date()
              }
            }
          }
        );
        //  TODO 发送通知
        await ctx.json(true, 'success', { amount: 15 });
      } else {
        await ctx.json(false, '成功接受， 但奖励发放失败');
      }
    }
  });
}
